#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# description: Test monitor enable/disable

test_simple_monitor() {
    local monitor="$1"
    local prefix="$2" # nested monitors

    echo 1 > "monitors/$prefix$monitor/enable"
    grep -q "$monitor$" enabled_monitors

    echo 0 > "monitors/$prefix$monitor/enable"
    ! grep -q "$monitor$" enabled_monitors

    echo "$monitor" >> enabled_monitors
    grep -q 1 "monitors/$prefix$monitor/enable"

    echo "!$monitor" >> enabled_monitors
    grep -q 0 "monitors/$prefix$monitor/enable"
}

test_container_monitor() {
    local monitor="$1"
	local nested

    echo 1 > "monitors/$monitor/enable"
    grep -q "^$monitor$" enabled_monitors

    for nested_dir in "monitors/$monitor"/*; do
        [ -d "$nested_dir" ] || continue
        nested=$(basename "$nested_dir")
        grep -q "^$monitor:$nested$" enabled_monitors
    done
	test -n "$nested"

    echo 0 > "monitors/$monitor/enable"
    ! grep -q "^$monitor$" enabled_monitors

    for nested_dir in "monitors/$monitor"/*; do
        [ -d "$nested_dir" ] || continue
        nested=$(basename "$nested_dir")
        ! grep -q "^$monitor:$nested$" enabled_monitors
    done

    echo "$monitor" >> enabled_monitors
    grep -q 1 "monitors/$monitor/enable"

    for nested_dir in "monitors/$monitor"/*; do
        [ -d "$nested_dir" ] || continue
        nested=$(basename "$nested_dir")
        grep -q "^$monitor:$nested$" enabled_monitors
    done

    echo "!$monitor" >> enabled_monitors
    grep -q 0 "monitors/$monitor/enable"

    for nested_dir in "monitors/$monitor"/*; do
        [ -d "$nested_dir" ] || continue
        nested=$(basename "$nested_dir")
		test_simple_monitor "$nested" "$monitor/"
    done
}

for monitor_dir in monitors/*; do
    monitor=$(basename "$monitor_dir")

    if find "$monitor_dir" -mindepth 1 -type d | grep -q .; then
        test_container_monitor "$monitor"
    else
        test_simple_monitor "$monitor"
    fi
done

! echo non_existent_monitor > enabled_monitors
! grep -q "^non_existent_monitor$" enabled_monitors
